package com.reactor.demo;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author jing
 * @description
 * @date 2018/12/9 0009 17:38
 */
@Slf4j
public class WebClinetDemo {

    @Test
    public void testWebClient() throws InterruptedException {
        WebClient webClient = WebClient.create("http://localhost:8080");
        Mono<String> response = webClient.get().uri("/date")
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(log::info);
        TimeUnit.SECONDS.sleep(1);
    }

    @Test
    public void testWebClient2() {
        WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
        webClient.get().uri("/message")
                .accept(MediaType.TEXT_PLAIN)
                .exchange()//与retrieve一样用来获取返回值
                .flatMapMany(r -> r.bodyToFlux(String.class))
                .doOnNext(log::info)
                .blockLast();//在收到最后一个元素前会阻塞，响应式业务场景中慎用
    }

    @Test
    public void testWebClient3(){
        WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
        webClient.get().uri("/message")
                .accept(MediaType.TEXT_PLAIN)
                .retrieve()
                .bodyToFlux(String.class)
                .log()
                .take(10)//由于/message是一个无限流，这里取前10个，会导致流被取消；
                .blockLast();
    }
}
